package hua.updateapk;

import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.support.v4.content.FileProvider;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;

public class MainActivity extends AppCompatActivity {

    private String mSavePath;//apk保存地址
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button apkUpdate = (Button) findViewById(R.id.apk_update);
        apkUpdate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String httpUrl = "http://192.168.1.3/app-debug.apk";
                downFile(httpUrl);
            }
        });
    }

    public void downFile(final String mVersion_path) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {//检查sd是否挂载
                    if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                        String sdPath = Environment.getExternalStorageDirectory() + "/";
                        mSavePath = sdPath + "Mydowload";
                        Log.d(TAG, "run: mSavePath = " + mSavePath);
                        File dir = new File(mSavePath);
                        if (!dir.exists())
                            dir.mkdir();

                        if (dir != null) {
                            Log.d(TAG, "run: dir is ok");
                        }
                        // 下载文件
                        HttpURLConnection conn = (HttpURLConnection) new URL(mVersion_path).openConnection();
                        conn.connect();
                        InputStream is = conn.getInputStream();
                        File apkFile = new File(mSavePath, "app-debug.apk");
                        FileOutputStream fos = new FileOutputStream(apkFile);
                        int count = 0;
                        byte[] buffer = new byte[1024];
                        while (true) {
                            int numread = is.read(buffer);
                            count += numread;
                            Log.d(TAG, "run: count = " + String.valueOf(count));
                            // 下载完成
                            if (numread < 0) {
                                Log.d(TAG, "run: dowload over");
                                break;
                            }
                            fos.write(buffer, 0, numread);
                        }
                        fos.close();
                        is.close();
//                        installAPK();
                        installApkFile(MainActivity.this, mSavePath + "/app-debug.apk");
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /*
   * 下载到本地后执行安装
   */
    protected void installAPK() {
        File apkFile = new File(mSavePath, "app-debug.apk");
        if (!apkFile.exists())
            return;
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + apkFile.toString());
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        this.startActivity(intent);
    }

    public static void installApkFile(Context context, String filePath) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(context, "hua.updateapk.fileprovider", new File(filePath));
            intent.setDataAndType(contentUri, "application/vnd.android.package-archive");
        } else {
            intent.setDataAndType(Uri.fromFile(new File(filePath)), "application/vnd.android.package-archive");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        }
        context.startActivity(intent);
    }
}


